import { getAssetPath } from '@/utils';
import React, { JSX, useEffect, useState } from 'react'

const Time: React.FC = () => {
    const [date, setDate] = useState<Date>(new Date());

    useEffect(() => {
        let animationFrameId: number;
        let lastUpdateTime = Date.now();

        const updateDate = () => {
            const now = Date.now();
            if (now - lastUpdateTime >= 1000) { // 每秒检查一次
                const newDate = new Date();
                const oldMinutes = date.getHours() * 60 + date.getMinutes();
                const newMinutes = newDate.getHours() * 60 + newDate.getMinutes();

                if (newMinutes !== oldMinutes) { // 只有分钟变了才更新状态
                    setDate(newDate);
                }
                lastUpdateTime = now;
            }
            animationFrameId = requestAnimationFrame(updateDate);
        };

        animationFrameId = requestAnimationFrame(updateDate);

        return () => cancelAnimationFrame(animationFrameId);
    }, [date]);
    // 获取星期
    const getWeekday = (date: Date): string => {
        return new Intl.DateTimeFormat("zh-CN", { weekday: "long" }).format(date);
    };
    const formatDate = (date: Date): JSX.Element => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const week = getWeekday(date)
        return (
            <>
                <div className='text-[18px] tracking-[3px]'>16℃~26℃</div>
                <div className='mx-[70px] text-[18px] tracking-[3px] flex'>晴转多云<img src={getAssetPath("wether.png")} alt="" className='w-[20px]' /></div>
                <div className='mr-[100px] tracking-[2px]'>{week}</div>
                <div className='flex flex-col items-center justify-center'>
                    <div className='font-bold text-[26px] tracking-[7px] mb-[5px]'>
                        {hours}:{minutes}
                    </div>
                    <div className='text-[12px] tracking-[1px]'>
                        {year}年{month}月{day}日
                    </div>
                </div>
            </>
        )
    };

    return (
        <div className='absolute top-[2.5%] right-[2%] flex items-center'>
            {formatDate(date)}
        </div>
    );
}

export default Time